package org.bigmouth.framework.web.action.json;


import org.bigmouth.framework.response.ResponseData;
import org.bigmouth.framework.web.action.BasicActionSupport;

import com.googlecode.jsonplugin.JSONException;

/**
 * <p>
 * 基于JSON格式响应给客户端的Action基类，该类主要是封装一些公共的响应方法。
 * </p>
 * 具体其他实现建议扩展该类。 <br/>
 * JSON数据结构：
 * 
 * <pre>
 *     "resultCode" : -1,
 *     "resultMessage" : '保存失败',
 *     "resultData" : [
 *          {
 *              ...
 *          }
 *      ]
 * </pre>
 * 
 * @author Allen / 2012-9-28
 */
public class JsonActionSupport extends BasicActionSupport {

    private static final long serialVersionUID = 7378383958484802189L;

    protected void doResponse(int statusCode, String message, Object data) throws JSONException {
        try {
            String result = ResponseData.getResult(statusCode, message, data);
            doResponseQuietly(result);
        }
        catch (JSONException e) {
            throw e;
        }
    }

    protected void doResponse(int statusCode, String message) throws JSONException {
        try {
            String result = ResponseData.getResult(statusCode, message);
            doResponseQuietly(result);
        }
        catch (JSONException e) {
            throw e;
        }
    }

    protected void doResponse(int statusCode) throws JSONException {
        try {
            String result = ResponseData.getResult(statusCode, "");
            doResponseQuietly(result);
        }
        catch (JSONException e) {
            throw e;
        }
    }

    protected void succeed() {
        try {
            doResponse(ResponseData.SUCCEED);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void succeed(Object ojbect) {
        try {
            doResponse(ResponseData.SUCCEED, "", ojbect);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void failed() {
        try {
            doResponse(ResponseData.FAILED);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void failed(String message) {
        try {
            doResponse(ResponseData.FAILED, message);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void failed(int statusCode, String message) {
        try {
            doResponse(statusCode, message);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void timeout() {
        try {
            doResponse(ResponseData.TIME_OUT);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
